import React, {Fragment} from "react";
import { Button, Form, Input, Popconfirm, message, Select, Tree, Row, Col,Spin, Icon, Popover} from 'antd';
import {getNavMenu, delMenu, addMenu, updateMenu} from '../../../service/api';
import './MenuManagement.less';

const TreeNode = Tree.TreeNode;
const FormItem = Form.Item;
const Option = Select.Option;

const iconArr = ["lock", "unlock", "bars", "book", "cloud-o", "code-o", "copy", "credit-card", "file", "folder",
    "hdd", "inbox", "laptop", "search", "setting", "share-alt", "user", "tag-o", "team", "customer-service",
    "database", "copyright", "table", "profile"];


class MenuChoose extends React.Component{

    state = {
        visible: false
    }


    handleVisibleChange = (visible) => {
        this.setState({ visible });
    }

    chooseIcon = (e)=> {
        this.setState({
            visible: false,
        });
        this.props.getIcon(e.target.id);
    }

    render() {

        let menuIcon = [];
        for(let i in iconArr){
            menuIcon.push(<Icon key={i} onClick={this.chooseIcon} className="menuIconChoose" id={iconArr[i]} type={iconArr[i]} />)
        }

        return (
            <Popover className="menuModal"
                     content={menuIcon}
                     title="菜单图标"
                     trigger="click"
                     visible={this.state.visible}
                     onVisibleChange={this.handleVisibleChange}
            >
                <Icon type={this.props.icon} className="curP" />
            </Popover>
        )
    }

}


class MenuManagement extends React.Component {

    state = {
        permissions: JSON.parse(localStorage.permissions),
        data: [],
        showData: {},
        new: true,
        loading: true,
        delId: [],
        modId: ""
    }

    componentDidMount() {
        this.getData();
    }

    getData = () => {
        let self = this;
        this.setState({loading: true})
        getNavMenu().then(function (data) {
            if(data.code === 200){
                self.setState({data: data.data, loading: false})
            }

        })
    }

    renderTreeNodes = (data) => {
        return data.map((item) => {
            if (item.children) {
                return (
                    <TreeNode title={item.name} key={item.menuId} dataRef={item}>
                        {this.renderTreeNodes(item.children)}
                    </TreeNode>
                );
            }
            return <TreeNode {...item} title={item.name} dataRef={item} />;
        });
    }

    setNew = () => {
        this.setState({new: true, showData: []})
    }

    onCheck = (value) => {
        this.setState({
            delId: value
        })


    }

    onSelect = (value, item) => {

        this.setState({new: false, showData: item.selectedNodes[0].props.dataRef, modId: value})
    }

    del = () => {
        let self = this;
        console.log(this.state.delId)
        delMenu({menuIds: this.state.delId}).then(function (data) {
            if(data.code === 200){
                sessionStorage.removeItem("menu");
                message.success("删除成功");
                self.getData();
            }
        })
    }

    chooseItem = () => {
        message.info("请选择需要删除的菜单")
    }

    handleSubmit = (e) => {
        e.preventDefault();
        let self = this;
        this.props.form.validateFields((err, values) => {
            if (!err) {
                self.setState({loading: true})
                if (this.state.new) {
                    values.parentId = values.parentId.key;
                    values.isDelete = 0
                    values.icon = self.state.showData.icon;
                    // if (values.parentId == "0") {
                    //     values.type = 0
                    //     values.icon = self.state.showData.icon
                    // } else {
                    //     values.type = 1
                    //     values.icon = self.state.showData.icon
                    // }

                    addMenu(values).then(function (data) {
                        if (data.code === 200) {
                            sessionStorage.removeItem("menu");
                            message.success("添加成功!");
                            self.getData();
                        } else {
                            message.error(data.msg)
                        }
                    })
                } else {
                    values.parentId = values.parentId.key;
                    values.isDelete = 0;
                    values.type = this.state.showData.type;
                    values.icon = this.state.showData.icon;
                    values.perms = this.state.showData.perms;
                    updateMenu(this.state.modId, values).then(function (data) {
                        if (data.code === 200) {
                            sessionStorage.removeItem("menu");
                            message.success("修改成功!");
                            self.getData();
                        } else {
                            message.error(data.msg)
                        }
                    })
                }
            }
        })
    }

    chooseIcon = (obj)=> {
        let data = this.state.showData;
        data.icon = obj;
        this.setState({
            showData: data
        })
    }

    render(){

        let tree = this.renderTreeNodes(this.state.data);
        const { getFieldDecorator } = this.props.form;

        let tplList = <FormItem label="父级">{getFieldDecorator('parentId',
            {
                rules: [{ required: true, message: '请选择父级' }],
                initialValue: {key: this.state.showData.parentId?this.state.showData.parentId:"", label: this.state.showData.parentName?this.state.showData.parentName:""}
            })(
            <Select style={{width: 200}} placeholder="请选择父级" labelInValue>
                <Option value='0'>顶级</Option>
                { this.state.data.length ? this.state.data.map((item) => (
                    <Option key={item.menuId}>{item.name}</Option>
                )) : <Option value='0'>顶级</Option> }
            </Select>
        )}</FormItem>



        return (
            <Spin spinning={this.state.loading}>
                <div className="menuManagement">
                    <div className="contentBody">
                        <Row>
                            {this.state.permissions["sys:menu:add"]?<Button type="primary" onClick={this.setNew}>新增</Button>: true}
                            {this.state.permissions["sys:menu:delete"]?
                                this.state.delId.length?<Popconfirm placement="leftBottom" title={`确定删除:选中菜单吗?`} onConfirm={this.del} okText="确定" cancelText="取消">
                                    <Button type="danger" ghost className="ml10">删除</Button>
                                </Popconfirm>:<Button type="danger" ghost className="ml10" onClick={this.chooseItem}>删除</Button>:true}

                        </Row>
                        <Row className="mt10">
                            <Col span={6} className="borderLine" style={{marginRight: "10px"}}>
                                <Tree checkable onCheck={this.onCheck} onSelect={this.onSelect}>
                                    {tree}
                                </Tree>
                            </Col>
                            <Col span={16} className="borderLine">
                                <Form onSubmit={this.handleSubmit}>
                                    {tplList}
                                    <FormItem label="名称">
                                        {getFieldDecorator('name',{
                                            rules: [{ required: true, message: '名称' }],
                                            initialValue: this.state.showData.name
                                        })(
                                            <Input placeholder="名称" />
                                        )}
                                    </FormItem>

                                    <FormItem label="排序">
                                        {getFieldDecorator('orderNum',{
                                            rules: [{ required: true, message: '排序' }],
                                            initialValue: this.state.showData.orderNum
                                        })(
                                            <Input placeholder="排序" />
                                        )}
                                    </FormItem>
                                    <FormItem label="链接">
                                        {getFieldDecorator('url',{
                                            rules: [{ required: true, message: '链接' }],
                                            initialValue: this.state.showData.path
                                        })(
                                            <Input placeholder="链接" />
                                        )}
                                    </FormItem>
                                    <FormItem label="图标">
                                        {getFieldDecorator('icon',{
                                            rules: [{ required: true, message: '图标' }],
                                            initialValue: this.state.showData.icon?this.state.showData.icon:"bars"
                                        })(
                                            <MenuChoose getIcon={this.chooseIcon} icon={this.state.showData.icon?this.state.showData.icon:"bars"} />
                                        )}
                                    </FormItem>
                                    {this.state.new?<Button type="primary" htmlType="submit">新增</Button>:<Button type="primary" htmlType="submit" onClick={this.mod}>修改</Button>}
                                </Form>
                            </Col>
                        </Row>
                    </div>
                </div>
            </Spin>
        )
    }

}
const MenuManagementForm = Form.create()(MenuManagement);
export default MenuManagementForm;